import React, { PureComponent } from 'react';
import { Transfer, Tree } from 'antd';
import styles from './treeTransfer.less';

const { TreeNode } = Tree;
// Customize Table Transfer
const isChecked = (selectedKeys, eventKey) => selectedKeys.indexOf(eventKey) !== -1;

const generateTree = (treeNodes = [], checkedKeys = [], titleFiled = 'title') =>
  treeNodes.map(({ children, ...props }) => (
    <TreeNode {...props} title={props[titleFiled]} disabled={checkedKeys.includes(props.key)} key={props.key}>
      {generateTree(children, checkedKeys, titleFiled)}
    </TreeNode>
  ));

class TreeTransfer extends PureComponent {
  // eslint-disable-next-line no-useless-constructor

  // eslint-disable-next-line no-useless-constructor
  constructor(props) {
    super(props);
  }

  render() {
    const { dataSource, value, treeHeight = 'auto', rowKey = 'key', titleFiled = 'title', ...restProps } = this.props;
    const transferDataSource = [];
    function flatten(list = []) {
      list.forEach(item => {
        transferDataSource.push(item);
        flatten(item.children);
      });
    }
    flatten(dataSource);
    return (
      <div className={styles.transferTree}>
        <Transfer
          style={{
            height: '100%',
            overflow: 'auto',
          }}
          {...restProps}
          targetKeys={value}
          rowKey={record => record[rowKey]}
          dataSource={transferDataSource}
          className="tree-transfer"
          render={item => item[titleFiled]}
          showSelectAll
        >
          {({ direction, onItemSelect, selectedKeys }) => {
            if (direction === 'left') {
              const checkedKeys = [...selectedKeys, ...value];
              return (
                <div className={styles.treebox}>
                  <Tree
                    blockNode
                    checkable
                    checkStrictly
                    defaultExpandAll
                    checkedKeys={checkedKeys}
                    onCheck={(
                      _,
                      {
                        node: {
                          props: { eventKey },
                        },
                      },
                    ) => {
                      onItemSelect(eventKey, !isChecked(checkedKeys, eventKey));
                    }}
                    onSelect={(
                      _,
                      {
                        node: {
                          props: { eventKey },
                        },
                      },
                    ) => {
                      onItemSelect(eventKey, !isChecked(checkedKeys, eventKey));
                    }}
                  >
                    {generateTree(dataSource, value, titleFiled)}
                  </Tree>
                </div>
              );
            }
          }}
        </Transfer>
      </div>
    );
  }
}

export default TreeTransfer;
